import React, { ReactElement } from 'react';
import moment from 'moment';

import { Dispatch, State } from './types';
import navigator from '../../util/navigator';
import inAppPurchaseModule, {
  Error
} from '../../util/native/inAppPurchaseModule';
import { toolTipOpen, modalOpen, modalClose } from '../../util/global';
import Alert from '../../components/Alert';
import Buy from './components/Buy';
import { InPayErrCode } from '../../util/native/inAppPurchaseModule/constant';
import { getUserInfo } from '../../store/user';
import { constant } from '../../util/native';
import { CoinApi } from '../../api';
import { Data, IAPCommodityInfo } from '../../api/coin/getIAPCommodityList';
import { pointToYuan } from '../../util/transformMoney';

let dispatch: Dispatch;
let state: State;
let reload = (): void => {};

export default (d: Dispatch, s: State): void => {
  dispatch = d;
  state = s;
};

export const getReload = (): void => {
  reload();
};

export const setSelectedItem = (value: number): void => {
  dispatch({ type: 'SET_SELECTED_ITEM', value });
};

export const setData = (value: Data): void => {
  dispatch({ type: 'SET_DATA', value });
};

export const fetchFailed = (): void => {
  dispatch({ type: 'FETCH_FAILED' });
};

export const coinHistory = (): void => {
  navigator.push('RechargeRecord');
};

export const getCoinList = (): void => {
  reload = (): void => {
    getCoinList();
  };
  CoinApi.getIAPCommodityList()
    .then((res): void => {
      if (res.code === 0) {
        const { commodities, userYutouCoinAmount } = res.data;
        setData({
          commodities: commodities.map(
            (item): IAPCommodityInfo => ({
              ...item,
              price: pointToYuan(item.price),
              yutouCoinNum: pointToYuan(item.yutouCoinNum)
            })
          ),
          userYutouCoinAmount
        });
        inAppPurchaseModule.initCommodities(commodities);
      }
    })
    .catch((): void => {
      fetchFailed();
    });
};

export const openBuy = (): void => {
  modalOpen({
    Type: (): ReactElement => <Buy />,
    needBack: true
  });
};

export const buySuccess = (orderId: string): void => {
  const { isGuest } = getUserInfo();
  modalOpen({
    Type: (): ReactElement => (
      <Alert
        title="充值成功"
        sureDesc="确定"
        subTitle={isGuest ? orderId : ' '}
        sureAction={(): void => {
          if (isGuest) {
            const time = moment().unix();
            constant.setKey(`${time}`, orderId, 'orderInfo');
          } else {
            modalClose();
          }
          getCoinList();
        }}
      />
    ),
    needBack: true
  });
};

export const buyFail = (desc: string): void => {
  modalOpen({
    Type: (): ReactElement => (
      <Alert
        title="充值失败，请重试"
        sureDesc="确定"
        subTitle={desc}
        sureAction={modalClose}
      />
    ),
    needBack: true
  });
};

export const credit = (): void => {
  const { data, selectedItemIndex } = state;
  const { commodities } = data;

  if (commodities && commodities.length === 0) return;

  const buyId = commodities[selectedItemIndex].commodityId;

  const currentDeviceIsJailbroken = inAppPurchaseModule.currentDeviceIsJailbroken();
  const canMakePayments = inAppPurchaseModule.canMakePayments();
  if (!canMakePayments) {
    toolTipOpen({ desc: '用户禁止应用内付费购买' });
    return;
  }

  if (currentDeviceIsJailbroken) {
    toolTipOpen({ desc: '越狱用户不允许充值' });
    return;
  }

  openBuy();

  inAppPurchaseModule.startBuy(buyId, (res: Error): void => {
    if (res.code === InPayErrCode.InPayCheckOrderSuccess) {
      buySuccess(res.msg);
    } else if (
      res.code === InPayErrCode.InPayBuyFail ||
      res.code === InPayErrCode.InPayBuyCancel ||
      res.code === InPayErrCode.InPayHaveBuy ||
      res.code === InPayErrCode.InPayTransactionDelay ||
      res.code === InPayErrCode.InPayCreateOrderFail ||
      res.code === InPayErrCode.InPayCheckOrderFail ||
      res.code === InPayErrCode.InPayNoProduct
    ) {
      buyFail(res.msg);
    }
  });
};

export const sureCredit = (): void => {
  const { isGuest } = getUserInfo();
  if (isGuest) {
    navigator.push('Login', { isBind: true });
    return;
  }

  modalOpen({
    Type: (): ReactElement => (
      <Alert
        title="充值提示"
        sureDesc="确认充值"
        subTitle={`蜜蜂币充值后不能退款、提现或转赠，\n仅限在蜜蜂小班ios版本中消费`}
        cancelAction={modalClose}
        cancelDesc="取消"
        sureAction={credit}
      />
    ),
    needBack: true
  });
};
